import React from "react";
import MarkdownIt from "markdown-it";
import styles from "./ChatMessage.module.css";
import CodeBlock from "./CodeBlock";
import { MessageRole } from "../../core/types/chat";

interface ChatMessageProps {
    content: string;
    role: MessageRole;
    timestamp: number;
    streaming?: boolean;
}

const roleNameMap = {
    user: "用户",
    assistant: "AI助手",
    system: "系统",
    tool: "工具助手",
};

const md = new MarkdownIt({
    html: false,
    breaks: true,
    linkify: true,
    highlight: function (str: string, lang: string) {
        return `<pre class="language-${lang}"><code>${str}</code></pre>`;
    },
});

const ChatMessage: React.FC<ChatMessageProps> = ({
    content,
    role,
    timestamp,
}) => {
    const formattedTime = new Date(timestamp).toLocaleTimeString("zh-CN", {
        hour: "2-digit",
        minute: "2-digit",
    });

    // 处理代码块
    const processContent = (content: string) => {
        const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g;
        const parts = [];
        let lastIndex = 0;
        let match;

        while ((match = codeBlockRegex.exec(content)) !== null) {
            // 添加代码块前的文本
            if (match.index > lastIndex) {
                const text = content.slice(lastIndex, match.index);
                parts.push(
                    <div
                        key={`text-${lastIndex}`}
                        dangerouslySetInnerHTML={{ __html: md.render(text) }}
                    />,
                );
            }

            // 添加代码块
            parts.push(
                <CodeBlock
                    key={`code-${match.index}`}
                    language={match[1] || ""}
                    code={match[2]}
                />,
            );

            lastIndex = match.index + match[0].length;
        }

        // 添加剩余的文本
        if (lastIndex < content.length) {
            const text = content.slice(lastIndex);
            parts.push(
                <div
                    key={`text-${lastIndex}`}
                    dangerouslySetInnerHTML={{ __html: md.render(text) }}
                />,
            );
        }

        return parts;
    };

    return (
        <div className={`${styles.message} ${styles[role]}`}>
            <div className={styles.avatar}>{role === "user" ? "👤" : "🤖"}</div>
            <div className={styles.content}>
                <div className={styles.header}>
                    <span className={styles.role}>{roleNameMap[role]}</span>
                    <span className={styles.time}>{formattedTime}</span>
                </div>
                <div className={styles.text}>{processContent(content)}</div>
            </div>
        </div>
    );
};

export default ChatMessage;
